package service.dataBase;

import java.util.ArrayList;

import commons.business_db.interfaces.DBConnection;

import business.entities.Article;
import business.entities.Category;
import service.exceptions.BadQueryInputException;
import service.exceptions.DBAlreadyRunningException;
import service.exceptions.DBWritingException;
import service.exceptions.EmptyDBException;
import service.exceptions.NotHereException;

public class BusinessConector implements DBConnection {

	@Override
	public void articleToDB(Article art) throws DBWritingException {
		try {
			DataBase db=new DataBase();
			String info=art.toString();
			String[] data=info.split(",");
			String[] inputData={data[0],data[2],data[3],data[1]};
			//return this.name + "," + this.descr + "," + this.price + ","+ this.cat.toString() + "," + aux;
			try{
				db.insert().insertIntoProductos(inputData);
			}catch(DBInsertException e){
				throw new DBWritingException(null);
			}
			db.closeConnection();
		} catch (DBAlreadyRunningException e) {
			// TODO Auto-generated catch block
			throw new DBWritingException(null);
		}
		
	}

	@Override
	public Article getArticle(int primaryKey) throws NotHereException {
		DataBase db;
		String condition="id_producto="+String.valueOf(primaryKey);
		String table="productos";
		String fields="nombre,precio,id_producto,id_categoria,descripcion";
		ArrayList<Object[]> res=new ArrayList<Object[]>();
		try {
			db = new DataBase();
			res = db.runAQuery().selectFromTable(table, fields, condition);
			db.closeConnection();
			
			return new Article(String.valueOf(res.get(0)[0]),String.valueOf(res.get(0)[4]),Double.valueOf(String.valueOf(res.get(0)[1])),null,getCategory(Integer.valueOf(String.valueOf(res.get(0)[3]))),Integer.valueOf(String.valueOf(res.get(0)[2])));
		} catch (DBAlreadyRunningException e) {
			e.printStackTrace();
		} catch (BadQueryInputException e) {
			e.printStackTrace();
		}
		return null;
	}

	private Category getCategory(int primaryKey){
		DataBase db;
		String condition="id_categoria="+String.valueOf(primaryKey);
		String table="categorias";
		String fields="categoria,descripcion";
		ArrayList<Object[]> res=new ArrayList<Object[]>();
		
		try {
			db = new DataBase();
			res = db.runAQuery().selectFromTable(table, fields, condition);
			db.closeConnection();
		} catch (DBAlreadyRunningException e) {
			e.printStackTrace();
		} catch (BadQueryInputException e) {
			e.printStackTrace();
		}
		return new Category(String.valueOf(res.get(0)[0]),primaryKey,String.valueOf(res.get(0)[1]));
	}
	
	
	@Override
	public Article[] getAllArticles() throws EmptyDBException {

		return null; 
	}

	@Override
	public void deleteArticle(int primaryKey) throws DBWritingException {
		// TODO Auto-generated method stub
		
	}

}
